package com.daiziru.im.server;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.daiziru.common.constant.Constants;
import com.daiziru.im.handle.MsgHandler;
import com.daiziru.im.handle.MsgHandlerFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.Map;

/**
 * 作者：無言
 * 时间：2022/12/23 17:42
 * 描述：永无BUG
 * 消息处理器
 */
@Slf4j
public class ImWsMsgHandler implements IWsMsgHandler {

    /**
     * 握手时的方法
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        // 绑定个人通道（个人绑定的群聊）
        String userId = httpRequest.getParam("userId"); //获取前端连接tio通道时传过来的userId
        log.info("{} --------------> 用户正在握手！", userId);
        Tio.bindUser(channelContext, userId);
        return httpResponse;
    }

    /**
     * 握手完成之后
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @throws Exception
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        // 绑定群聊通道，群名称叫做：e-group-study
        Tio.bindGroup(channelContext, Constants.IM_GROUP_NAME);
        log.info("{} --------------> 已绑定群！", channelContext.getId());
    }

    /**
     * 接收字节类型的消息
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    /**
     * 接收字符类型的消息
     * @param wsRequest
     * @param s是一个json字符串，包含消息的type,和data
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {

        log.info("接收到消息-----------------------》{}", s);
        Map map = JSONUtil.toBean(s, Map.class);
        String type = MapUtil.getStr(map, "type");
        String data = MapUtil.getStr(map, "data");
        //根据消息类型获取消息处理器
        MsgHandler msgHandler = MsgHandlerFactory.getMsgHandler(type);
        // 处理消息
        msgHandler.handler(data, wsRequest, channelContext);

        return null;
    }

    /**
     * 关闭握手
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }


}
